<?php

namespace App\Http\Logic\Api;

use AlibabaCloud\Darabonba\Stream\StreamUtil;
use AlibabaCloud\SDK\Ocrapi\V20210707\Models\RecognizeIdcardRequest;
use AlibabaCloud\SDK\Ocrapi\V20210707\Ocrapi;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class AliIdCard
{
    public static function createClient(): Ocrapi
    {
        $config = new Config([
            "accessKeyId" => env("ALIBABA_CLOUD_ACCESS_KEY_ID"),
            "accessKeySecret" => env('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
        ]);
        $config->endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new Ocrapi($config);
    }

    /**
     * @throws Exception
     */
    public static function info($path){
        $client = self::createClient();
        $bodyStream = StreamUtil::readFromFilePath($path);
        $recognizeIdcardRequest = new RecognizeIdcardRequest([
            "body" => $bodyStream
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $client->recognizeIdcardWithOptions($recognizeIdcardRequest, $runtime);
            $data = $resp->toMap();
            $data = json_decode($data['body']['Data'], true);

            return $data['data']['face']['data'] ?? [];
        }
        catch (Exception $error) {
            throw new Exception($error->getMessage());
        }
    }
}
